package com.example.luke.cashorderingsystem.Activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.example.luke.cashorderingsystem.Adapter.GoodPaymentAdapter;
import com.example.luke.cashorderingsystem.Common.CommonActivity;
import com.example.luke.cashorderingsystem.Database.DingHanDB;
import com.example.luke.cashorderingsystem.Dialog.GetCashDialog;
import com.example.luke.cashorderingsystem.Model.Good;
import com.example.luke.cashorderingsystem.Model.Operator;
import com.example.luke.cashorderingsystem.Model.PurchaseReport;
import com.example.luke.cashorderingsystem.R;
import com.example.luke.cashorderingsystem.Util.GlobalFunction;
import com.example.luke.cashorderingsystem.Util.MIReaderUtils;
import com.example.luke.cashorderingsystem.http.HttpClient;
import com.example.luke.cashorderingsystem.http.HttpResponseHandler;
import com.example.luke.cashorderingsystem.http.NetWorkConstant;
import com.google.gson.Gson;

import android.Manifest;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 17/11/2016.
 */

public class PaymentActivity extends CommonActivity {

    @InjectView(R.id.item_List)ListView itemList;
@InjectView(R.id.total_price)TextView total_price;

    GoodPaymentAdapter paymentAdapter;
    private GetCashDialog getCashDialog;

    private ArrayList<Good> shoppingList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_activity_layout);
        ButterKnife.inject(this);
        setBarTitle(GlobalFunction.getString(this,R.string.bill));
        showBackButton();
            initView();
        initNFCParam();

    }
    String returnMoney;


    @Override
    public void initView() {
        super.initView();

        shoppingList=(ArrayList<Good>)getIntent().getSerializableExtra("shopbag");
        paymentAdapter =new GoodPaymentAdapter(this,shoppingList);
        itemList.setAdapter(paymentAdapter);
        checkCurrentPrice();


        getCashDialog=new GetCashDialog(this,totalPrice);

        getCashDialog.setGetCashListener(new GetCashDialog.GetCashListener() {
            @Override
            public void payMoney(String money) {



            }

            @Override
            public void finishPayment() {
               // initTicketID();

                savePurchaseRecord();
                updateStoredNumber();
                setResult(RESULT_OK);
                finish();


              String content=  MIReaderUtils.reformatTicketContent(ticketID,shoppingList);

            reader.startPrintText(content);
            reader.stopPrinter();

            }
        });







    }

    private void updateStoredNumber(){

        for (Good good:shoppingList){
          good.setStoredNumber(String.valueOf(Integer.valueOf(good.getStoredNumber())-good.getPurchaseCount()));
          Good.updateGoodStoreNumber(this,good);
        }
    }
    public String ticketID;


    private void savePurchaseRecord(){




        int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);

        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {

            ticketID=GlobalFunction.getOnlyID(this);
        }

        String dateTime=GlobalFunction.getCurrentDateTime();
        String httpDateTime=purchaseTime();


        for (Good good:shoppingList){

            PurchaseReport report=new PurchaseReport();
            report.setTicketID(ticketID);
            report.setCommodityID(good.getId());
            report.setCommodityName(good.getName());
            report.setVolume(good.getPurchaseCount());
            report.setPrimeCost(good.getPriceOut());
            report.setSaleCost(good.getPriceOut());
            report.setCost(good.getTotalPrice());
            report.setRestoredNum(Integer.valueOf(good.getStoredNumber()));
            report.setDisCount(good.getDisoountable());
            report.setDateTime(dateTime);
            report.setDateTimeCopy(httpDateTime);
            report.setEmployeeID(Operator.getIntance().getEmployeeID());
            report.setPayMode(0);
            PurchaseReport.insertReport(this,report);



        }





       // GlobalFunction.printTextByTag(PurchaseReport.getPurchaseReport(this).size()+"");

    }

    private String purchaseTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }



    Double totalPrice=0.;



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

     if (requestCode==0){

     }

    }



    private   void checkCurrentPrice(){

        GlobalFunction.printTextByTag(shoppingList+"");

    try {

    for (int i=0;i<shoppingList.size();i++){
        Good goods=shoppingList.get(i);
        totalPrice=totalPrice+Double.valueOf(goods.getTotalPrice());


    }


    total_price.setText( String.format(Locale.getDefault(),"%.2f",totalPrice)+"元");

    }catch (Exception e){


        GlobalFunction.printTextByTag("error");

    }


    }


    public void getMoney(View view){//收钱

        getCashDialog.show();
        getCashDialog.reset();
    }
}
